<?php
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;

class LawyerCenterController extends CenterController {

    protected $layout = 'layouts.lawyercenter';

    public function __construct()
    {
    	parent::__construct();
    }

    public function main() {
    	$user = User::find(Auth::user()->id);
    	$user->load('lawyer');
    	$userArr = $user->toArray();
    	$workScopeStr = $userArr['lawyer']['work_scope'];
    	$workScopeArr = explode(",", $workScopeStr);
    	$questions_count = Post::where('posts.status', POST::STATUS_NEW)
    			->where('posts.type',POST::TYPE_QUESTION)
    			->whereIn('posts.post_category', $workScopeArr)
    			->count();
    	$order_count = Post::leftjoin('post_thread', 'post_thread.post_id', '=', 'posts.id')
    			->where('posts.status', Post::STATUS_NEW)
    			->whereIn('posts.type', array(Post::TYPE_PAY_PHONE, Post::TYPE_PAY_TEXT))
    			->where('post_thread.user_id', Auth::user()->id)
    	->count();
    	$data = [];
    	$data['order_count'] = $order_count;
    	$data['avatar'] = UtilsHelper::getImage($userArr['avatar'], "img/dfimg.png");
    	
        return $this->makeView( 'center.lawyer.main', $data);
    }

    /**
     * 我的资料
     */
    public function info() {
        $this->user->load('lawyer');
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $posts = Input::all();

            $rules = array (
                'sex' => array('regex:/^(male|female)$/i'),
                'practice_period' => array('regex:/^(1to3|3to5|5to10|10)$/i'),
                'position' => array('regex:/^(lawyer|senior_lawyer|partner)$/i')
            );
            $messages = array(
                'sex.regex' => '性别选项错误',
                'practice_period.regex' => '执业年限选线错误',
                'position.regex' => '律师类型错误'
            );

            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }

            // save
            try {
            	$posts = UtilsHelper::filter_sensitive_word($posts);             //敏感词过滤
                $user = User::updateLawyer($this->user->id, $posts);
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '服务器暂时无法响应，请稍后再试。',
                    503
                );
            }
        } else {
            $user = $this->user;
        }
        
        $userArray = $user->toArray();
        $userArr = [];
        $userArr['is_verified'] = $user->isVerifiedLawyer();
        $userArr['id'] = $user['id'];
        $userArr['nikname'] = $user['nikname'];
        $userArr['realname'] = $user['realname'];
        $userArr['phone'] = $user['phone'];
        $userArr['email'] = $user['email'];
        $userArr['province'] = $user['province'];
        $userArr['city'] = $user['city'];
        $userArr['district'] = $user['district'];
        $userArr['city_name'] =AreaHelper::areaCodeToName($userArray['city']);
        $userArr['district_name'] =AreaHelper::areaCodeToName($userArray['district']);
        $userArr['province_name'] =AreaHelper::areaCodeToName($userArray['province']);
        $userArr['score'] = $user['score'];
        $userArr['status'] = $user['status'];
        $userArr['money'] = round(Wallet::getMoney($this->user->id));
        $userArr['avatar'] = UtilsHelper::getImage($userArray['avatar'], "img/dfimg.png");
        $userArr['unread_counts'] = $this->getUnreadCounts($this->user);
        $userArr['bg_image'] = UtilsHelper::getImage($userArray['lawyer']['bg_image'], "img/dfimg.png");
        $userArr['work_scope'] = UtilsHelper::getActualWorkScopes($userArray['lawyer']['work_scope']);
        
        return $this->makeView('center.lawyer.info', $userArr);
    }
    
    protected function getUnreadCounts($user) {
        $unreadCounts = [];
        $status = [
            Post::STATUS_NEW, 
            Post::STATUS_REPLIED, 
            Post::STATUS_WAIT_FOR_EVALUATION, 
            Post::STATUS_COMPLETE, 
            Post::STATUS_CANCELLED];
        $unreadCounts['question'] = Post::getUnreadCountForAssignedLawyer($user->id, [Post::TYPE_QUESTION], $status);
        $unreadCounts['pay_text'] = Post::getUnreadCountForAssignedLawyer($user->id, [Post::TYPE_PAY_TEXT], $status);
        $unreadCounts['pay_phone'] = Post::getUnreadCountForAssignedLawyer($user->id, [Post::TYPE_PAY_PHONE], $status);
        $unreadCounts['pay_company'] = Post::getUnreadCountForAssignedLawyer($user->id, [Post::TYPE_PAY_COMPANY], $status);
        $types = [Post::TYPE_PAY_TEXT, Post::TYPE_PAY_PHONE, Post::TYPE_PAY_COMPANY];
        $unreadCounts['shopping'] = Post::getUnreadCountForAssignedLawyer($user->id, $types, [Post::STATUS_WAIT_PAY]);
        $unreadCounts['letter'] = StationLetterUser::getUnreadCount();
        return $unreadCounts;
    }

    /**
     * 认证律师
     */
    public function becomeLawyer() {
        $this->user->load('lawyer');
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $posts = Input::all();

            $rules = array (
                'sex' => array('regex:/^(male|female)$/i'),
                'practice_period' => array('regex:/^(1to3|3to5|5to10|10)$/i'),
                'position' => array('regex:/^(lawyer|senior_lawyer|partner)$/i')
            );
            $messages = array(
                'sex.regex' => '性别选项错误',
                'practice_period.regex' => '执业年限选线错误',
                'position.regex' => '律师类型错误'
            );

            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }

            // save
            try {
                $posts = UtilsHelper::filter_sensitive_word($posts);             //敏感词过滤
                $user = User::updateLawyer($this->user->id, $posts);
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '服务器暂时无法响应，请稍后再试。',
                    503
                );
            }

            $userArr = $user->toArray();
            $userArr['avatar'] = UtilsHelper::getImage($userArr['avatar'], "img/dfimg.png");
            return $this->makeView('center.lawyer.info', array('user' => $userArr));
        } else {
            $workScopeList = UtilsHelper::workScope();
            $lawyerArr = $this->user->toArray();
            $lawyerArr['city_name'] =AreaHelper::areaCodeToName($lawyerArr['city']);
            $lawyerArr['district_name'] =AreaHelper::areaCodeToName($lawyerArr['district']);
            $lawyerArr['province_name'] =AreaHelper::areaCodeToName($lawyerArr['province']);
            $lawyerArr['lawyer']['license_file'] = UtilsHelper::getImage($lawyerArr['lawyer']['license_file'], "img/dfimg.png");
            $lawyerArr['lawyer']['ID_img'] = UtilsHelper::getImage($lawyerArr['lawyer']['ID_img'], "img/dfimg.png");
            $lawyerArr['lawyer']['work_scope'] = UtilsHelper::getActualWorkScopes($lawyerArr['lawyer']['work_scope']);
            $lawyerArr['avatar'] = UtilsHelper::getImage($lawyerArr['avatar'], "img/dfimg.png");
            return $this->makeView('center.lawyer.become_lawyer', 
                array(
                    'user' => $lawyerArr,
                    'work_scope' => $workScopeList
                )
            );
        }
    }
    
    /**
     * 更改密码
     */
    public function resetPass() {
        $this->user->load('lawyer');
        $id = $this->user->id;
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $posts = Input::all();

            // old password should match the existing value
            Validator::extend ( 'old_password', function ($attr, $value, $parameters) use( $id ) {
                $credentials = array (
                    'id' => $id,
                    'password' => $value
                );
                return Auth::validate($credentials);
            } );

            // old password and new password should not be the same
            Validator::extend ( 'new_password_diff', function ($attr, $value, $parameters) use( $posts ) {
                return ($posts['old_password'] != $posts['new_password']);
            } );

            // the two new passes should be the same
            Validator::extend ( 'new_passwords_match', function ($attr, $value, $parameters) use( $posts ) {
                return ($posts['new_password'] == $posts['new_password_retype']);
            } );

            $rules['old_password']='required|old_password';
            $rules['new_password']='required|between:6,18|new_password_diff';
            $rules['new_password_retype']='required|new_passwords_match';

            $messages = array(
                'old_password.required' => '请填写原始密码',
                'new_password.required' => '请填写新密码',
                'new_password.new_password_diff' => '新密码不可以和旧密码一样',
                'new_password_retype.required' => '请再填写一次新密码',
                'old_password.old_password' => '原始密码填写不正确',
                'new_password.between' => '新密码格式不正确',
                'new_password_retype.new_passwords_match' => '请确保两次输入的新密码是一致的',
            );
            
            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }

            try {
                $oldPwd = $this->user->password;
                $this->user->password = $posts ['new_password'];
                $this->user->save ();
                //同步修改环信密码
                $newPwd = $this->user->password;
                $result = new Easemob();
                $options = array(
                        'username' => $this->user->id,
                        'password' => $oldPwd,
                        'newpassword' => $newPwd
                );
                $result_re = $result->editPassword($options);
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '咨询律师失败，请稍后再试。',
                    503
                );
            }
            return $this->makeView('center.reset_pass', '成功更改密码');
        } else {
            return $this->makeView('center.reset_pass');
        }
    }
  
    /**
     * 已关注我的用户
     */
    public function customerFollowed() {
        $follows = User::leftJoin('follows', 'user.id', '=', 'follows.user_id')
            ->select(
                'user.id', 
                'user.avatar', 
                'user.realname', 
                'user.signature',
                'user.city',
                'follows_count',
                'follows.created_at'
                // 已关注我多少年
            )
            ->where('follows.follow_id', Auth::user()->id)
            // ->take($limit)
            // ->skip($offset)
            ->orderBy('follows.updated_at', 'DESC')
            ->groupBy('user.id')
            ->get();
        $followsArr = $follows->toArray();
        foreach($followsArr as &$follow) {
            $follow['city'] = AreaHelper::areaCodeToName($follow['city']);
            $follow['avatar'] = UtilsHelper::getImage($follow['avatar'], "img/dfimg.png");
        }
        return $this->makeView('center.lawyer.customer.followed', $followsArr);
    }

    /**
     * 我咨询过的律师
     */
    public function customerConsulted() {
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
                DB::raw('count(*) as posts_count'),
                'posts.creator_id',
                'user.avatar as avatar',
                'user.realname as realname',
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id',
                'posts.created_at',
                'posts.updated_at'
            )
            ->where('type', Post::TYPE_QUESTION)
            ->where('posts.status', POST::STATUS_REPLIED)
            ->where('post_thread.user_id', Auth::user()->id)
            ->orderBy('posts.updated_at', 'DESC')
            ->groupBy('posts.creator_id')
            ->get();
        $questionArr = $questions->toArray();
        $questionArr = $this->addComments($questionArr);
        return $this->makeView('center.lawyer.customer.consulted', $questionArr);
    }

    /**
     * 全部的咨询
     */
    public function questionAll() {
    	$input = Input::all();
    	$cat_id = Input::get('cat_id', 0);
    	$page = Input::get('page', 1);
    	$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
    	$offset = ($page-1) * $rows_per_page;
    	$order = Input::get('order', 'latest');
    	$orderby = 'updated_at';
    	$direction = 'DESC';
    	if ($order == 'chronological') {
    		$direction = 'ASC';
    	}
    	
    	$rules = array (
    			'cat_id' => 'numeric|min:1',
    			'page' => 'numeric|min:1',
    			'rows_per_page' => 'numeric|min:1',
    			'city_id' => 'numeric|min:1',
    			// 'published' => 'date'
    	);
    	$messages = array(
    			'cat_id.numeric' => 'cat_id需要是数字',
    			'cat_id.min' => 'cat_id不能少于1',
    			'page.numeric' => 'page需要是数字',
    			'rows_per_page.numeric' => 'rows_per_page需要是数字',
    			'city_id.numeric' => 'city_id需要是数字'
    	);
    	$validator = Validator::make ( $input, $rules, $messages );
    	if ($validator->fails()) {
    		// the given data did not pass validation
    		return $this->makeView(
    				'errors.400',
    				$validator->errors(),
    				400
    		);
    	}
    	
    	
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->leftJoin('evaluate', 'evaluate.item_id', '=', 'posts.id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id',
                'user.avatar as creator_avatar',
                'user.realname as creator_realname',
                'posts.created_at',
                'posts.updated_at',
                'evaluate.score as evaluate_score',
                'evaluate.comment as evaluate_comment')
    		->where('posts.type',POST::TYPE_QUESTION)
            ->where('post_thread.user_id', $this->user->id)
            ->where('posts.lawyer_visible', Post::LAWYER_VISIBLE)
            ->take($rows_per_page)
            ->skip($offset)
            ->orderBy('updated_at', 'DESC')
            ->get();
		foreach($questions as $question){
			$question['type'] = $question->getType();
			$question['status'] = $question->getStatus();
			$question['post_category'] = $question->getPostCatKey();
			$question->creator_avatar = UtilsHelper::getImage($question->creator_avatar, 'img/dfimg.png');
		}
        $questionArr = $questions->toArray();
        return $this->makeView('center.lawyer.question.all', $questionArr);
    }

    /**
     * 已经完成了的咨询
     */
    public function questionComplete() {
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->leftJoin('evaluate', 'evaluate.item_id', '=', 'posts.id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id',
                'user.avatar as creator_avatar',
                'user.realname as creator_realname',
                'posts.created_at',
                'posts.updated_at',
                'evaluate.score as evaluate_score',
                'evaluate.comment as evaluate_comment')
            ->whereIn('posts.status', array(POST::STATUS_COMPLETE,POST::STATUS_WAIT_FOR_EVALUATION))
    		->where('posts.type',POST::TYPE_QUESTION)
            ->where('post_thread.user_id', $this->user->id)
            ->where('posts.lawyer_visible', Post::LAWYER_VISIBLE)
            ->orderBy('updated_at', 'DESC')
            ->get();
		foreach($questions as $question){
			$question['type'] = $question->getType();
			$question['status'] = $question->getStatus();
			$question['post_category'] = $question->getPostCatKey();
		}
        $questionArr = $questions->toArray();
        return $this->makeView('center.lawyer.question.complete', $questionArr);
    }

    /**
     * 已经被处理的咨询
     */
    public function questionReplied() {
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id',
                'user.avatar as creator_avatar',
                'user.realname as creator_realname',
                'posts.created_at',
                'posts.updated_at')
            ->where('posts.status', POST::STATUS_REPLIED)
    		->where('posts.type',POST::TYPE_QUESTION)
            ->where('post_thread.user_id', $this->user->id)
            ->where('posts.lawyer_visible', Post::LAWYER_VISIBLE)
            ->orderBy('updated_at', 'DESC')
            ->get();
		foreach($questions as $question){
			$question['type'] = $question->getType();
			$question['status'] = $question->getStatus();
			$question['post_category'] = $question->getPostCatKey();
		}
        $questionArr = $questions->toArray();
        return $this->makeView('center.lawyer.question.replied', $questionArr);
    }
    
	public function getQuestion($id){
		$question = Post::find($id);
		return $question;
	}
    
    /**
     * 咨询详细
     */
    public function questionView($id){
    	$post = $this->getQuestion($id);
    	if(!$post){
    		return $this->makeView('errors.400', '请求错误', 400);
    	}
    	$post->load('postAttach');
        $postArr = $post->toArray();
    	$data=array();
    	$data['id'] = $id;
    	$data['type'] = $post->getType();
    	$data['title'] = $postArr['title'];
    	$data['content'] = $postArr['content'];
    	$data['status_code'] = $postArr['status'];
    	$data['status'] = $post->getStatus();
    	$data['title'] = $postArr['title'];
    	$data['created_at'] = $postArr['created_at'];
    	$data['updated_at'] = $postArr['updated_at'];
    	$data['lawyer'] = $post->getLawyerName();
    	$data['comments'] = $post->getComments();
    	$data['postAttachs'] = $post->postAttach->toArray();
    	return $this->makeView('center.lawyer.question.view', $data);
    }

    /**
     * 系统自动匹配的我的咨询
     */
    public function questionNew() {
    	$input = Input::all();
    	$cat_id = Input::get('cat_id', 0);
    	$page = Input::get('page', 1);
    	$rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
    	$offset = ($page-1) * $rows_per_page;
        $user = $this->user;
        $user->load('lawyer');
        $userArr = $user->toArray();
        $workScopeStr = $userArr['lawyer']['work_scope'];
        $workScopeArr = explode(",", $workScopeStr);
        $questions = Post::leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.creator_id as creator_id',
                'user.avatar as creator_avatar',
                'user.realname as creator_realname',
                'posts.created_at',
                'posts.updated_at')
            ->where('posts.status', POST::STATUS_NEW)
    		->where('posts.type',POST::TYPE_QUESTION)
            ->whereIn('posts.post_category', $workScopeArr)
            ->take($rows_per_page)
            ->skip($offset)
            ->orderBy('updated_at', 'DESC')
            ->get();

		foreach($questions as $question){
			$question['type'] = $question->getType();
			$question['status'] = $question->getStatus();
			$question['post_category'] = $question->getPostCatKey();
			$question->creator_avatar = UtilsHelper::getImage($question->creator_avatar, 'img/dfimg.png');
		}
        $questionArr = $questions->toArray();
        $questionArr = $this->addComments($questionArr);
        return $this->makeView('center.lawyer.question.new', $questionArr);
    }

    public function questionRecycled() {
        $this->layout->content = View::make('center.lawyer.question.recycled');
    }
    /**
     * 我的跟帖
     */
    public function blogReply(){
        
        $input = Input::all();
        $page = Input::get('page', 1);
        $rows_per_page = Input::get('rows_per_page', PaginationHelper::ROWS_PER_PAGE);
        $offset = ($page-1) * $rows_per_page;
        $orderby = 'created_at';
        $direction = 'DESC';
        $rules = array (
                'page' => 'numeric|min:1',
                'rows_per_page' => 'numeric|min:1',
        );
        $messages = array(
                'page.numeric' => 'page需要是数字',
                'rows_per_page.numeric' => 'rows_per_page需要是数字'
        );
        $validator = Validator::make ( $input, $rules, $messages );
        if ($validator->fails()) {
            // the given data did not pass validation
            return $this->makeView(
                    'errors.400',
                    $validator->errors(),
                    400
            );
        }
        
        $myReplys = Article::leftjoin('evaluate', 'articles.id', '=', 'evaluate.item_id')
            ->leftjoin('user', 'user.id', '=', 'articles.creator_id')
            ->select(
                    'articles.id as article_id',
                    'articles.law_cat',
                    'articles.img',
                    'articles.title',
                    'articles.info',
                    'articles.hits',
                    'articles.comments as comment_count',
                    'articles.likes',
                    'articles.downs',
                    'articles.creator_id',
                    'articles.created_at',
                    'articles.collects_count',
                    'articles.creator_id',
                    'evaluate.comment',
                    'user.id as creator_id',
                    'user.realname as creator_realname',
                    'user.avatar as creator_avatar'
                )
            ->where('evaluate.creator_id', Auth::user()->id)
            ->where('evaluate.type', Evaluate::TYPE_ARTICLE)
            ->take($rows_per_page)
            ->skip($offset)
            ->get();
        $articleArr = $myReplys->toArray();
        foreach($articleArr as &$article) {
            $article['creator_avatar'] = UtilsHelper::getImage($article['creator_avatar'], "img/dfimg.png");
        }
        return $this->makeView('center.lawyer.blog.reply', $articleArr, 200);
    }


    /**
     * 查看评价详情
     */
    public function evaluateView($id){
    	$data = [];
    	$post = $this->getQuestion($id);
        if(!$post){
            return $this->makeView('errors.400', '咨询不存在,请求错误', 400);
        }
    	$data['type'] = $post->getType();
    	$data['post_category'] = $post->getPostCatKey();
    	$data['title'] = $post->title;
    	$data['content'] = $post->content;
    	$data['evaluate_score'] = "";
    	$data['evaluate_content'] = "";
    	$data['created_at'] = "";
    	$evaluate = Evaluate::where('type', Evaluate::TYPE_QUESTION)->where('item_id', $id)->first();
		//dd($evaluate->toArray());
    	if($evaluate){
    		$data['score'] 			 = $evaluate->score;
    		$data['comment'] 		 = $evaluate->comment;
    		$data['created_at'] 	 = $evaluate->created_at->toDateTimeString();
			$data['difference_date'] = UtilsHelper::differenceFormat($data['created_at']);
    		$data['tags'] 			 = explode(',' ,$evaluate->tags);
			$user 					 = User::find($evaluate->creator_id);
    		$data['realname'] 		 = !empty($user->nickname) ? $user->nickname : '匿名';
    	}
    		return $this->makeView('center.lawyer.evaluate', $data, 200);
    }
    
    /**
     * 删除受理的咨询
     */
    public function questionRemove($id){
    	$post = $this->getQuestion($id);
    	if(!$post){
    		return $this->makeView('errors.404', '该咨询不存在', 404);
    	}
		$postThread = PostThread::where('post_id', $id)->first();
		if($postThread->user_id != Auth::user()->id){
			return $this->makeView('errors.400', '只有受理律师才可以删除', 400);
		}
    	if($post->status == Post::STATUS_COMPLETE || $post->status == Post::STATUS_CANCELLED ||$post->status == Post::STATUS_WAIT_PAY){
    		$post->lawyer_visible = Post::CUSTOMER_UNVISIBLE;
    		$post->save();
    		//     		$order = $post->getOrder($id);
    		// 	    	if($order){
    		// 	    		$order = Order::find($order->id);
    		// 	    		$order->delete();
    		// 	    	}
    		return $this->makeView('general.201', '删除成功', 201);
    	}
    }
    
    /**
     * 我的帖子列表
     */
    public function blogList() {
    	return $this->articlesList();
    }
    
    /**
     * 删除帖子
     */
    public function blogRemove($id){
    	$article = Article::find($id);
    	if(!$article){
    		return $this->makeView(
    				'errors.404',
    				'该文章不存在',
    				404
    			);
    	}
    	if($article->creator_id != Auth::user()->id){
    		return $this->makeView(
    				'errors.400',
    				'您没有权限删除该文章',
    				400
    			);
    	}
    	try{
    		$articleInfo = ArticleInfo::find($id);
    		DB::transaction(function() use($article, $articleInfo){
    			$article->delete();
    			$articleInfo->delete();
    		});  		
    	}catch (Exception $ex){
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试',
    				503
    			);
    	}
    	return Redirect::to('center/lawyer/blog/list');
    }

    /**
     * 创建帖子
     */
    public function blogCreate() {
	   	return $this->articleCreate();
    	//$this->layout->content = View::make('center.lawyer.blog.create');
    }

    /**
     * 帖子详情
     */
    public function blogView($id) {
    	$article = Article::find($id);
    	$articleInfo = ArticleInfo::find($id);
    	if(!$article || !$articleInfo){
    		return $this->makeView(
    				'errors.404',
    				'该文章不存在',
    				404
    		);
    	}
   	try{
   		$article = Article::find($id)->toArray();
   		$articleInfo = ArticleInfo::find($id)->toArray();
   		$className = ArticleClass::find($article['class'])->toArray();
   		$workScopes = UtilsHelper::workScope();
   		$data = array_merge((array)$article, (array)$articleInfo);
   		$data['className'] = $className['name'];
        $default= "img/default_imgs/[]".rand(1,19).".png";
        $data['img'] = UtilsHelper::getImage($data['img'],$default);
   		return $this->makeView('center.lawyer.blog.view',$data);
   	}catch (Exception $ex){
   		Log::error($ex);
   		return $this->makeView(
   				'errors.503',
   				'服务请暂时无法响应，请稍后再试',
   				503	
   			);
   	}
    	
    	
    	//$this->layout->content = View::make('center.lawyer.blog.view');
    }

    /**
     * 修改帖子
     *
     */
    public function blogEdit($id){
    	try{
    		$article = Article::find($id)->toArray();
    		$articleInfo = ArticleInfo::find($id);
    		if(!$article || !$articleInfo){
    			return $this->makeView(
    					'errors.404',
    					'该文章不存在',
    					404
    				);		
    		}
    		$articleInfo = $articleInfo->toArray();
    		$articleClasss = ArticleClass::all()->toArray();
    		$workScopes = UtilsHelper::workScope();
    		$data = array_merge((array)$article, (array)$articleInfo);
    		$data['workscopes'] = $workScopes;
    		$data['articleClasss'] = $articleClasss;
    		$data['visibility'] = $data['visibility'];
    		return $this->makeView('center.lawyer.blog.create',$data);
    	}catch(Exception $ex){
    		Log::error($ex);
    		return $this->makeView(
    				'errors.503',
    				'服务器暂时无法响应，请稍后再试',
    				503
    			);
    	}
    }
    /**
     * 帖子草稿
     */
    public function blogDraft() {
        // 分类 & 权限
        $querycondition = ['creator_id'=>Auth::user()->id];
        $querycondition['status'] = Article::STATUS_DRAFTS;
        $data=Article::where($querycondition)->get()->toArray();
        for($i=0;$i<count($data);$i++){
        	$classname = ArticleClass::find($data[$i]['class']);
        	if(empty($classname)){
        		$data[$i]['classname'] = '未分类';
        	}else{
        		$data[$i]['classname'] = $classname->name;
        	}
        }
        return $this->makeView('center.lawyer.blog.draft', $data); 
    }

    /**
     * 我的圈子
     */
    public function group() {
        $this->layout->content = View::make('center.lawyer.group');
    }

    /**
     * 免费咨询
     */
    public function freeQuestion($status) {
        $this->layout->content = View::make('center.lawyer.question_order.free_question', ['status' => $status]);
    }


    /**
     * 图文咨询
     */
    public function payText($status) {
        $this->layout->content = View::make('center.lawyer.question_order.pay_text', ['status' => $status]);
    }

    /**
     * 电话咨询
     */
    public function payPhone($status) {
        $this->layout->content = View::make('center.lawyer.question_order.pay_phone', ['status' => $status]);
    }


    /**
     * 小薇企服
     */
    public function payCompany($status) {
        $this->layout->content = View::make('center.lawyer.question_order.pay_company', ['status' => $status]);
    }

    /**
     * 咨询管理
     */
    public function myQuestion() {
        $this->layout->content = View::make('center.lawyer.my_question');
    }

    /**
     * 我的订单
     */
    public function myOrder() {
        $this->layout->content = View::make('center.lawyer.my_order');
    }

    /**
     * 咨询详细
     */
    public function orderView($id){
        $post = $this->getQuestion($id);
        if(!$post){
            return $this->makeView('errors.400', '请求错误', 400);
        }
        $post->load('postAttach');
        $postArr = $post->toArray();
        $data=array();
        $data['post_id'] = $id;
        $data['type'] = $post->getType();
        $data['title'] = $postArr['title'];
        $data['content'] = $postArr['content'];
        $data['status_code'] = $postArr['status'];
        $data['status'] = $post->getStatus();
        $data['title'] = $postArr['title'];
        $data['created_at'] = $postArr['created_at'];
        $data['updated_at'] = $postArr['updated_at'];
        $data['lawyer'] = $post->getLawyerName();
        $data['comments'] = $post->getComments();
        $data['postAttachs'] = $post->postAttach->toArray();
        return $this->makeView('center.lawyer.question_order.view', $data);
    }
    
}
